//
//  ZXY_MOMOOperation.m
//  Lover_BridgeiOS
//
//  Created by 宇周 on 15/12/1.
//  Copyright © 2015年 宇周. All rights reserved.
//

#import "ZXY_MOMOOperation.h"
#import "AppDelegate.h"

@implementation ZXY_MOMOOperation
+ (NSManagedObjectContext *)context
{
    NSManagedObjectContext *context = [(AppDelegate *)
                                       [UIApplication sharedApplication].delegate managedObjectContext];
    return context;
}

+ (BOOL)saveModel:(NSString *)modalName
      WithSaveDic:(NSDictionary *)dataDic
    andReflectDic:(NSDictionary *)reflectDic
{
    NSManagedObjectContext *context = [self context];
    NSManagedObject *modal     = [NSEntityDescription
                                  insertNewObjectForEntityForName:modalName
                                           inManagedObjectContext:context];
    
    for (NSString *currentKey in dataDic.allKeys) {
        id value = dataDic[currentKey];
        if([reflectDic.allKeys containsObject:currentKey])
        {
            [modal setValue:value forKey:reflectDic[currentKey]];
        }
    }
    NSError *error;
    BOOL isSuccess = [context save:&error];
    if(!isSuccess)
    {
        NSLog(@"error -> modal: %@ info: %@",modalName , error);
    }
    return isSuccess;
}


+ (BOOL)saveModel:(NSString *)modalName
      WithSaveDic:(NSDictionary *)dataDic
    andReflectDic:(NSDictionary *)reflectDic
withPredictFormat:(NSString *)format
     ifExistBlock:(BOOL (^)(NSManagedObjectContext *ctx, NSArray *mob)) findIt;
{
    BOOL isExit = [self modelExists:modalName withPredict:format];
    if (isExit) {
        if(findIt)
        {
            BOOL isGOON = findIt([self context] , [self findModels:modalName withPredict:format]);
            if(!isGOON)
            {
                NSLog(@"saveModel 由于数据存在，不再继续执行存储操作");
                return NO;
            }
        }
        
    }
    return [self saveModel:modalName WithSaveDic:dataDic andReflectDic:reflectDic];
}


+ (NSArray *)findModels:(NSString *)modalName
            withPredict:(NSString *)predict
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:modalName inManagedObjectContext:[self context]];
    [fetchRequest setEntity:entity];
    if(predict)
    {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:predict];
        [fetchRequest setPredicate:predicate];
    }
    NSError *error = nil;
    NSArray *fetchedObjects = [[self context] executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"error -> findModels : %@ withError: %@",modalName , error);
    }
    return fetchedObjects;
}

+ (BOOL)updateModel:(NSString *)modalName
        withSaveDic:(NSDictionary *)dataDic
      andReflectDic:(NSDictionary *)reflectDic
  withPredictFormat:(NSString *)format
{
    NSArray *modals = [self findModels:modalName withPredict:format];
    for(NSManagedObject *one in modals)
    {
        for(NSString *currentKey in dataDic.allKeys)
        {
            if([reflectDic.allKeys containsObject:currentKey])
            {
                NSString *dbKey = reflectDic[currentKey];
                id value        = dataDic[currentKey];
                [one setValue:value forKey:dbKey];
            }
        }
    }
    NSError *error;
    BOOL isSuccess = [[self context] save:&error];
    if(!isSuccess)
    {
        NSLog(@"updateModelError -> modal: %@ , error: %@",modalName , error);
    }
    return isSuccess;
}


+ (BOOL)deleteModel:(NSString *)modalName
        withPredict:(NSString *)predict
{
    if([self modelExists:modalName withPredict:predict])
    {
        NSArray *modals = [self findModels:modalName withPredict:predict];
        for (NSManagedObject *one in modals) {
            [[self context] deleteObject:one];
        }
        return YES;
    }
    else
    {
        NSLog(@"Nothing deleted");
        return NO;
    }
}


+ (BOOL)saveModels:(NSString *)modalName
      withSaveList:(NSArray *)listArr
    withReflectDic:(NSDictionary *)reflectDic
{
    BOOL result = YES;
    for(int i = 0 ; i<listArr.count ; i++)
    {
        NSDictionary *dicForSave = listArr[i];
        result = [self saveModel:modalName WithSaveDic:dicForSave andReflectDic:reflectDic];
        if(!result)
        {
            return NO;
        }
    }
    return result;
}

+ (BOOL)saveModels:(NSString *)modalName
      withSaveList:(NSArray *)listArr
    withReflectDic:(NSDictionary *)reflectDic
    andFindPredict:(NSArray<NSString *> *)format
       autoIndexes:(BOOL)autoIndex
        whenFindIt:(BOOL (^)(NSManagedObjectContext * , NSArray *)) findIt
{
    BOOL result = YES;
    NSManagedObjectContext *context = [self context];
    for(int i = 0 ; i < listArr.count ; i++)
    {
        NSDictionary *dicForSave = [listArr objectAtIndex:i];
        NSInteger findIndex = autoIndex ? 0 : i;
        if(format.count > 0)
        {
            if([self modelExists:modalName withPredict:[format objectAtIndex:findIndex]])
            {
                NSString *formatTemp = [format objectAtIndex:findIndex];
                NSArray *finds = [self findModels:modalName withPredict:formatTemp];
                if(findIt)
                {
                    BOOL isGoOn = findIt(context , finds);
                    if(!isGoOn)
                    {
                        continue;
                    }
                }
            }
            result = [self saveModel:modalName WithSaveDic:dicForSave andReflectDic:reflectDic];
            if(!result)
            {
                return NO;
            }
        }
        
    }
    return result;
}


+ (BOOL)modelExists:(NSString *)modalName
        withPredict:(NSString *)predict
{
    
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:modalName];
    if(predict)
    {
        [request setPredicate:[NSPredicate predicateWithFormat:predict]];
    }
    NSArray *requestArr = [[self context] executeFetchRequest:request error:nil];
    if(requestArr.count > 0)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
@end

@implementation ZXY_MOMOOperation (SAVE_AS_RETURN_MODAL)

+ (NSManagedObject *)saveModel:(NSString *)modalName
      WithSaveDic:(NSDictionary *)dataDic
    andReflectDic:(NSDictionary *)reflectDic
{
    NSManagedObjectContext *context = [self context];
    NSManagedObject *modal     = [NSEntityDescription
                                  insertNewObjectForEntityForName:modalName
                                  inManagedObjectContext:context];
    
    for (NSString *currentKey in dataDic.allKeys) {
        id value = dataDic[currentKey];
        if([reflectDic.allKeys containsObject:currentKey])
        {
            [modal setValue:value forKey:reflectDic[currentKey]];
        }
    }
    NSError *error;
    BOOL isSuccess = [context save:&error];
    if(!isSuccess)
    {
        NSLog(@"error -> modal: %@ info: %@",modalName , error);
    }
    return modal;
}

+ (NSArray *)updateModel:(NSString *)modalName
                     withSaveDic:(NSDictionary *)dataDic
                   andReflectDic:(NSDictionary *)reflectDic
               withPredictFormat:(NSString *)format
{
    NSArray *modals = [self findModels:modalName withPredict:format];
    for(NSManagedObject *one in modals)
    {
        for(NSString *currentKey in dataDic.allKeys)
        {
            if([reflectDic.allKeys containsObject:currentKey])
            {
                NSString *dbKey = reflectDic[currentKey];
                id value        = dataDic[currentKey];
                [one setValue:value forKey:dbKey];
            }
        }
    }
    NSError *error;
    BOOL isSuccess = [[self context] save:&error];
    if(!isSuccess)
    {
        NSLog(@"updateModelError -> modal: %@ , error: %@",modalName , error);
    }
    return modals;

}

@end
